package net.byg.util;

import net.byg.ftp.ContinueFTP;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class UploadAssetsUtil {

    public static void upload(ContinueFTP myFtp, String localDir, String serverDir) {
        try {
            String fileName = "";
            File file = new File(localDir);
            List<File> files = new ArrayList<File>();
            lookupFiles(files, file);

            for (File uploadFile : files) {
                fileName = uploadFile.getPath().substring(uploadFile.getPath().indexOf(localDir) + localDir.length() + 1).replaceAll("\\\\", "/");
                System.out.print(Thread.currentThread().getName()+"-[" + fileName + "]上传中... ");
                if (myFtp.ftpClient.changeWorkingDirectory("~" + serverDir)) { // linux
                    myFtp.ftpClient.changeWorkingDirectory("D:" + serverDir); // windwos
                }
                myFtp.ftpClient.deleteFile(new String(fileName.getBytes("GBK"), "iso-8859-1"));
                System.out.println(myFtp.upload(uploadFile.getPath(), fileName));
            }

            myFtp.disconnect();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private static void lookupFiles(List<File> list, File file) {
        File[] files = file.listFiles();
        for (File uploadFile : files) {
            if (uploadFile.isFile()) {
                list.add(uploadFile);
            } else if (uploadFile.isDirectory()) {
                lookupFiles(list, uploadFile);
            }
        }
    }
}
